/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package opengl;

import android.goalkeeper.GameThread;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 *
 * @author gokhan
 */
public class OpenGLRenderer implements GLSurfaceView.Renderer {

    private Ball mBall;
    private GameThread mThread;
    private float mBallRotation;
    private float mBallTranslate;

    public OpenGLRenderer(GameThread thread) {
        this.mThread = thread;
        mBall = new Ball(1, 25);
        mBallTranslate = -30f;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);

        gl.glClearDepthf(1.0f);
        //depth test required for 3d object drawing
        gl.glEnable(GL10.GL_DEPTH_TEST);
        //dept test function
        gl.glDepthFunc(GL10.GL_LEQUAL);

        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
                GL10.GL_NICEST);

        //TODO: Enable Anti-aliasing

        //start main thread because the suface is ready for drawing
        mThread.setRunning(true);
        mThread.start();

    }

    @Override
    public void onDrawFrame(GL10 gl) {
        //function is called for every frame
        //buffer and dept bit should be cleared
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        gl.glLoadIdentity();


        //MAIN DRAWING WILL BE DONE HERE FOR EVERY OBJECT

        //shift it a little far away so that cube can be seen
        gl.glTranslatef(0.0f, 0.0f, mBallTranslate);
        gl.glRotatef(mBallRotation, 1.0f, 1.0f, 1.0f);
        mBall.draw(gl);
        gl.glLoadIdentity();
        mBallRotation -= 0.9f;

        mBallTranslate += 0.3f;
        if (mBallTranslate >= -5f) {
            mBallTranslate = -30f;
        }


        //TODO: enable double buffering 
        //NOTE: couldn't find glSwapBUffer functions

    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }
}
